package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {
    @Autowired
    private SpecParamService paramService;
    @Autowired
    private SpecGroupService groupService;
    @Override
    public List<SpecGroupDTO> queryGroupByCategory(Long cid) {
        List<SpecGroup> specGroups = this.query().eq("category_id", cid).list();
        return SpecGroupDTO.convertEntityList(specGroups);
    }

    @Override
    public List<SpecGroupDTO> querySpecList(Long categoryId) {
        //查询规格组
        List<SpecGroupDTO> groupList = SpecGroupDTO.convertEntityList(query().eq("category_id", categoryId).list());
        if (CollectionUtils.isEmpty(groupList)){
            throw  new LyException(404,"该分类下的规格组不存在！");
        }
            //查询规格参数
            List<SpecParamDTO> paramList = paramService.queryParams(categoryId,null,null);
            //对规格参数分组，groupId一致的在一组中
            Map<Long, List<SpecParamDTO>> map = paramList.stream().collect(Collectors.groupingBy(SpecParamDTO::getCategoryId));
            //把参数放在group中
            for (SpecGroupDTO groupDTO : groupList) {
                groupDTO.setParams(map.get(groupDTO.getId()));
            }
        return groupList;
    }

    /**
     * 新增规格组
     * @param groupDTO
     */
    @Override
    public void saveGroup(SpecGroupDTO groupDTO) {
       SpecGroup specGroup=groupDTO.toEntity(SpecGroup.class);
       save(specGroup);
    }



    /**
     * 修改
     * @param groupDTO
     */
    @Override
    public void updateGroup(SpecGroupDTO groupDTO) {
        updateById(groupDTO.toEntity(SpecGroup.class));

    }

}
